#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

#define handle_error(res,msg) \
          if(res==-1){\
            perror(msg);\
            exit(EXIT_FAILURE);\
          } 


int main(int argc, const char *argv[]){
  int pipefd[2];
  pid_t son_pid;
  char buf; // 保存收到的数据

  // 判断是否获到参数
  if(argc!=2){
    fprintf(stderr,"%s,请填写要传递的消息！\n",argv[0]);
    exit(EXIT_FAILURE);
  }
  // 创建匿名管道
  if(pipe(pipefd)==-1){
    perror("pipe");
    exit(EXIT_FAILURE);
  }
  son_pid = fork();
  handle_error(son_pid,"fork");
  if(son_pid==0){ // 子进程从管道读取数据
    close(pipefd[1]);
    printf("子进程%d读取来自父进程%d发送的数据。。。。\n",
      getpid(),getppid());
    while(read(pipefd[0],&buf,1)>0){
      write(STDOUT_FILENO,&buf,1);
    }
    write(STDOUT_FILENO,"\n",1);
    close(pipefd[0]); //关闭读端
  }else{ // 父进程写数据到管道
    // 关闭读端
    close(pipefd[0]);
    printf("父进程%d向子进程%d发送数据:%s\n",
        getpid(),son_pid,argv[1]);
    // 向管道写入数据
    write(pipefd[1],argv[1],strlen(argv[1]));
    // 关闭写端
    close(pipefd[1]);
    waitpid(son_pid,NULL,0);    
  }
  return 0;
}
